package com.wxl.common.http

import android.text.TextUtils
import com.alibaba.fastjson.JSONObject
import com.wxl.common.util.Loog
import com.wxl.common.util.Toll
import java.lang.reflect.ParameterizedType

open class SerialHttpCallback<T> : AbsSerialHttpCallback<T>{


    constructor(dataKey: String) : super(dataKey)

    override fun success(data: String) {
        try {
            if(TextUtils.isEmpty(data)){
                mSerialHttpHandler?.sendSuccess(null as T)
                return
            }
            val dataType = findDataType()
            if(TextUtils.equals(dataType.toString(), String::class.java.name)){
                mSerialHttpHandler?.sendSuccess(data as T)
            } else if(data.startsWith("[") && data.endsWith("]")){
                val array = JSONObject.parseArray(data, dataType) as ArrayList<T>
                mSerialHttpHandler?.sendSuccess(array)
            } else if(data.startsWith("{") && data.endsWith("}")) {
                val obj = JSONObject.parseObject(data, dataType)
                mSerialHttpHandler?.sendSuccess(obj)
            } else {
                mSerialHttpHandler?.sendSuccess(data as T)
            }
        } catch (e:Exception){
            Loog.e(e.message.toString())
            if (isShowErrorMsg()) {
                Toll.toll("服务器返回数据错误")
            }
            mSerialHttpHandler?.sendError(e)
        }
    }




    open fun isShowErrorMsg(): Boolean {
        return true
    }

    override fun error(e: Throwable) {
        super.error(e)
        loadDataFailed(e)
    }

    open fun loadDataSuccess(data:T?){}

    open fun loadDataSuccess(datas:ArrayList<T>){}

    open fun loadDataFailed(e: Throwable){
    }

    internal open fun findDataType(): Class<T> {
        val superclass = javaClass.genericSuperclass
        if (superclass is ParameterizedType) {
            val arrayOfTypes = superclass.actualTypeArguments
            return arrayOfTypes[0] as Class<T>
        }
        return String::class.java as Class<T>
    }
}